"use strict";

/**
 * tag controller
 */

const { createCoreController } = require("@strapi/strapi").factories;

module.exports = createCoreController('api::tag.tag', ({ strapi }) => ({

    async batchUpdate(ctx, next) {

        try {
            const { body } = ctx.request
            let result = []
            if (Array.isArray(body)) {
                const data = body.map((o, i) => {
                    o.sort = i
                    return o
                })
                for (const item of data) {
                    const entry = await strapi.db.query('api::tag.tag').update({
                        where: { id: item.id },
                        data: {
                            sort: item.sort,
                        },
                    });
                    result.push(entry)
                }
                ctx.body = { data: result, message: 'success' }
            }

            else {
                ctx.body = { data: result, message: 'fail' }
            }
        } catch (err) {
            ctx.body = { data: null, message: err }
        }
    },

}));